<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>编辑文章</title>
    <link rel="stylesheet" href="" th:href="@{/lib/editormd/css/editormd.css}">
    <link rel="stylesheet" href="" th:href="@{/lib/layui/css/layui.css}">
    <style>
        html, body {
            height: 100%;
        }

        /*暂时处理编辑器高估*/
        #test-editor {
            min-height: 680px;
        }
    </style>
</head>

<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <div th:replace="fragment/header::header" ></div>
    <div th:replace="fragment/left-nav::left-nav" ></div>
    <div class="layui-body">
<!--添加编辑容器-->
        <form action="" class="layui-form" lay-filter="form">
    <div class="layui-form-item">
        <div class="layui-input-inline">
            <select name="interest" th:name="categoryId">
                <option value="" th:each="obj:${categories}" th:value="${obj.id}" th:text="${obj.name}"></option>
            </select>
        </div>
        <div class="layui-input-inline" style="width: 70%;margin-left:2%">
            <input type="text" lay-filter="title" name="title" style="background-color:rgb(255, 250, 227)"
                   class="layui-input" placeholder="请输入标题，100个字以内">
        </div>
        <div class="layui-input-inline">
            <input type="button" class="layui-btn" value="发布" id="publish">
        </div>
    </div>
    <div id="test-editor" class="layui-form-item" style="height: 100%">
        <div class="layui-input-block ">
            <textarea style="display:none;" class="layui-textarea" name="content"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">标签</label>
        <div class="layui-input-inline">
            <input type="text" name="title" lay-verify="tags"
                   autocomplete="off" placeholder="请输入标签，比如hello" class="layui-input" id="tagBtn">
        </div>
        <!--        <div class="layui-input-inline" id="tagSpans">-->

        <!--        </div>-->
    </div>
    <div class="layui-form-item" id="tagSpans">
    </div>
</form>
    </div>
    <div class="layui-footer">
        <!-- 底部固定区域 -->
        © layui.com - 底部固定区域
    </div>
</div>
<!--引入layui-->
<script th:src="@{/lib/layui/layui.js}"></script>
<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript" th:src="@{/lib/editormd/editormd.min.js}"></script>
<script>
    var editor;
    $(function () {
        editor = editormd("test-editor", {
            // width  : "100%",
            height: "100%",
            watch:false,//关闭默认的实时预览功能
            path: "/lib/editormd/lib/"
        });
    });

    layui.use(['jquery', 'form', 'layer','element'], function () {
        var $ = layui.jquery;
        var form = layui.form;
        var layer = layui.layer;
        var element=layui.element;
        $('#publish').click(function () {
            // 获取表单数据，发送请求到后端
            // 构建我们的tags 数据
            var tags = [];
            $('#tagSpans span').each(function () {
                var obj = {
                    "name": $(this).attr('data')
                };
                tags.push(obj);
            });
            var obj = {
                "title": $('input[name=title]').val(),
                "content": editor.getMarkdown(),
                "category": {
                    "id": $("select[name=categoryId]").val()
                },
                "tags": tags
            };

            $.ajax({
                    url: '/article',
                    type: 'post',
                    contentType: 'application/json',
                    data: JSON.stringify(obj),
                    success: function (data) {
                        if (data.code = 2000) {
                            if (data.data != null) {
                            }
                            layer.msg(data.msg, {
                                icon: 6,// 绿色成功笑脸
                                time: 1000
                            });
                        } else {
                            layer.msg(data.msg);
                        }
                    }
                }
            )
        })
        // 监听ctrl + v
        $('#test-editor').get(0).addEventListener('paste', function () {
            // 获取图片资源，通过ajax 发送过去
            var items = event.clipboardData && event.clipboardData.items;
            var file = null;
            if (items && items.length) {
                // 检索剪切板items
                for (var i = 0; i < items.length; i++) {
                    if (items[i].type.indexOf('image') !== -1) {
                        file = items[i].getAsFile();
                        break;
                    }
                }
            }
            if (file == null)
                return;
            var formData = new FormData();
            formData.append('file', file);
            $.ajax({
                url: '/up/image',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                beforeSend: function () {
                    layer.msg('<i class="layui-icon layui-icon-upload"></i>正在上传，客官别急..', {
                        time: 1500
                    });
                },
                success: function (data) {
                    // 获取markdownUrl ，写入当前文本当中
                    // var markdownUrl = data.markdownUrl;
                    // editor.insertValue(markdownUrl);
                    var obj = JSON.parse(data);
                    // 通过obj.data.url 可以得到url地址 address 为拼接的 图片地址写法
                    var url = obj.data.url;
                    if (url.toString().indexOf(".jpg") > 0 || url.toString().indexOf(".png") > 0) {
                        var address = '![](' + url + ')';
                        editor.insertValue(address)
                    } else {
                        alert('不合法的图片格式');
                    }
                },
                error: function (xhr, error) {
                    alert('error');
                }
            })
        })

        // 监听回车键入标签
        $('#tagBtn').get(0).addEventListener('keydown', function (ev) {
            if (ev.keyCode == 13) {
                // 获取这个里面的值
                var v = $(this).val();
                // 处理v 值，是否有已经存在
                var hasTag = false;
                $('#tagSpans input').each(function () {
                    var temp = $(this).val();
                    if (v == temp) {
                        hasTag = true;
                        return;
                    }
                })
                if (hasTag) {
                    $(this).val('');
                    return;
                }
                if (v === '') {
                    // 空内容不予处理
                    layer.msg('不能有空标签哦！',{
                        time:1500
                    })
                    return;
                }

                // var html = '<input type="button" class="layui-btn" value="'+v+'" /> ';
                var html = '<span class="layui-btn" data="' + v + '">' + v + '<i class="layui-icon-delete layui-icon" style="font-size: 30px; color: red;"></i></span>'
                // var html = '<input type="button" class="layui-btn" value="'+v+'" /> ';
                $(this).val('');
                $('#tagSpans').append(html);
                form.render();
            }
        })
        // 监听delete icon
        $(document).on('click', '#tagSpans i', function () {
            // 移除自身
            $(this).parent().remove();
        })
    })
</script>
</body>
</html>